package com.realtime.polling;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

/**
 * @author nieyong
 * @time 2012-8-21
 * @version 1.0
 */
@WebServlet(urlPatterns = "/polling/piggybackDemo")
public class PiggybackPollingDemo extends HttpServlet {
	private static final long serialVersionUID = 508319184090659631L;

	private final Random random = new Random();
	private final BlockingQueue<String> messages = new LinkedBlockingQueue<String>();
	private final Thread generator = new Thread("Event generator") {
		@Override
		public void run() {
			while (!Thread.currentThread().isInterrupted()) {
				try {
					Thread.sleep(random.nextInt(5000));
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
				messages.offer("At " + new Date());
			}
		}
	};

	@Override
	public void init() throws ServletException {
		generator.start();
	}

	@Override
	public void destroy() {
		generator.interrupt();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("FORM POSTED !");
		List<String> messages = new LinkedList<String>();
		this.messages.drainTo(messages);
		resp.setStatus(HttpServletResponse.SC_OK);
		resp.setContentType("application/json");
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("events", messages);
		jsonObj.put("formValid", true);

		resp.getWriter().write(jsonObj.toString());
		resp.getWriter().flush();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<String> messages = new LinkedList<String>();
		this.messages.drainTo(messages);
		resp.setStatus(HttpServletResponse.SC_OK);
		resp.setContentType("application/json");
		JSONObject jsonObj = new JSONObject();
		resp.getWriter().write(jsonObj.toString());
		resp.getWriter().flush();
	}
}